<script setup lang="ts">
import {
  getMemberOrderPreAPI,
  getMemberOrderPreNowAPI,
  getMemberOrderRepurchaseByIdAPI,
  postMemberOrderAPI,
} from '@/services'
import type { OrderPreResult } from '@/types'
import type { SelectorPickerOnChange } from '@uni-helper/uni-app-types'
import { computed, ref } from 'vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { useAddressStore } from '@/stores'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

interface Props {
  /* 立即购买所需参数 */
  skuId?: string
  count?: string
  addressId?: string
  /* 再次购买所需参数 */
  orderId?: string
}
const query = defineProps<Props>()
const orderPre = ref<OrderPreResult>()
// 获取订单信息
const getMemberOrderPreData = async () => {
  if (query.count && query.skuId) {
    // 立即购买订单
    const res = await getMemberOrderPreNowAPI({
      skuId: query.skuId,
      count: query.count,
      addressId: query.addressId,
    })
    orderPre.value = res.result
  } else if (query.orderId) {
    // 再次购买订单
    const res = await getMemberOrderRepurchaseByIdAPI(query.orderId)
    orderPre.value = res.result
  } else {
    // 预付订单
    const res = await getMemberOrderPreAPI()
    orderPre.value = res.result
  }
}
onLoad(async () => {
  uni.showLoading()
  await getMemberOrderPreData()
  // uni.hideLoading()
})

const addressStore = useAddressStore()
// 收货地址
const selectedAddress = computed(
  () =>
    addressStore.selectedAddress ||
    orderPre.value?.userAddresses[0] ||
    orderPre.value?.userAddresses.find((v) => v.isDefault),
)
onUnload(() => {
  // 页面卸载时，清除用户选中的收货地址
  addressStore.clearSelectedAddress()
})

// 配送时间表
const deliveryList = ref([
  { type: 1, text: '时间不限 (周一至周日)' },
  { type: 2, text: '工作日送 (周一至周五)' },
  { type: 3, text: '周末配送 (周六至周日)' },
])
const buyerMessage = ref('')
const activeIndex = ref(0)
const activeDelivery = computed(() => deliveryList.value[activeIndex.value])
// 修改配送时间
const onDeliveryChange: SelectorPickerOnChange = (e) => {
  activeIndex.value = e.detail.value
}

/* 提交订单 */
const onOrderSubmit = async () => {
  if (!selectedAddress.value?.id) {
    return uni.showToast({ icon: 'none', title: '请选择收货地址' })
  }
  const res = await postMemberOrderAPI({
    addressId: selectedAddress.value?.id,
    deliveryTimeType: activeDelivery.value.type,
    buyerMessage: buyerMessage.value,
    goods: orderPre.value!.goods.map((v) => ({ skuId: v.skuId, count: v.count })),
    payChannel: 2,
    payType: 1,
  })
  // 关闭当前页，再跳转订单详情页
  uni.redirectTo({ url: `/pagesOrder/detail/detail?id=${res.result.id}` })
}
</script>

<template>
  <scroll-view class="viewport" scroll-y enable-back-to-top>
    <!-- 收货地址 -->
    <navigator
      v-if="selectedAddress"
      class="shipment"
      hover-class="none"
      url="/pagesMember/address/address?from=order"
    >
      <view class="user"> {{ selectedAddress.receiver }} {{ selectedAddress.contact }} </view>
      <view class="address">
        {{ selectedAddress.fullLocation }} {{ selectedAddress.address }}
      </view>
      <text class="icon icon-right"></text>
    </navigator>
    <navigator
      v-else
      class="shipment"
      hover-class="none"
      url="/pagesMember/address/address?from=order"
    >
      <view class="address"> 请选择收货地址 </view>
      <text class="icon icon-right"></text>
    </navigator>
    <!-- 商品信息 -->
    <view class="goods">
      <navigator
        class="item"
        hover-class="none"
        v-for="item in orderPre?.goods"
        :key="item.skuId"
        :url="`/pages/goods/goods?id=${item.id}`"
      >
        <image class="picture" :src="item.picture" />
        <view class="meta">
          <view class="name ellipsis-1"> {{ item.name }} </view>
          <view class="attrsText ellipsis">{{ item.attrsText }}</view>
          <view class="prices">
            <view class="pay-price symbol">{{ item.payPrice }}</view>
            <view class="price symbol">{{ item.price }}</view>
          </view>
          <view class="count">x{{ item.count }}</view>
        </view>
      </navigator>
    </view>
    <!-- 配送及支付方式 -->
    <view class="related">
      <view class="item">
        <text class="text">配送时间</text>
        <picker :range="deliveryList" range-key="text" @change="onDeliveryChange">
          <view class="icon-fonts picker">{{ activeDelivery.text }}</view>
        </picker>
      </view>
      <view class="item">
        <text class="text">订单备注</text>
        <input
          v-model="buyerMessage"
          class="input"
          placeholder="选题，建议留言前先与商家沟通确认"
          :cursor-spacing="30"
        />
      </view>
    </view>
    <!-- 支付金额 -->
    <view class="settlement">
      <view class="item">
        <text class="text">商品总价: </text>
        <text class="number symbol">{{ orderPre?.summary.totalPrice.toFixed(2) || '0.00' }}</text>
      </view>
      <view class="item">
        <text class="text">运费: </text>
        <text class="number symbol">{{ orderPre?.summary.postFee.toFixed(2) || '0.00' }}</text>
      </view>
    </view>
    <!-- 底部占位空盒子 -->
    <view class="toolbar-height" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }"></view>
  </scroll-view>
  <!-- 底部工具栏 -->
  <view class="toolbar" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
    <view class="total-pay">
      <text>合计：</text>
      <text class="price symbol">{{ orderPre?.summary.totalPayPrice.toFixed(2) || '0.00' }}</text>
    </view>
    <view :class="['button', { disabled: !selectedAddress?.id }]" @tap="onOrderSubmit">
      提交订单
    </view>
  </view>
</template>

<style lang="scss">
page {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f4f4f4;
  overflow: hidden;
}

.symbol::before {
  margin-right: 5rpx;
  content: '¥';
  font-size: 80%;
}

/* 收货地址 */
.shipment {
  position: relative;
  margin: 20rpx;
  padding: 30rpx 30rpx 30rpx 84rpx;
  font-size: 26rpx;
  border-radius: 10rpx;
  background: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/locate.png)
    20rpx center / 50rpx no-repeat #fff;

  .icon {
    position: absolute;
    top: 50%;
    right: 20rpx;
    transform: translateY(-50%);
    font-size: 36rpx;
    color: #333;
  }

  .user {
    margin-bottom: 5rpx;
    color: #333;
  }

  .address {
    color: #666;
  }
}

/* 商品信息 */
.goods {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    padding: 30rpx 0;
    border-top: 1rpx solid #eee;

    &:first-child {
      border-top: none;
    }

    .picture {
      width: 170rpx;
      height: 170rpx;
      border-radius: 10rpx;
    }

    .meta {
      position: relative;
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      margin-left: 20rpx;
    }

    .name {
      font-size: 26rpx;
      color: #444;
    }

    .attrsText {
      // align-self: flex-start;
      position: absolute;
      top: 40rpx;
      left: 0;
      padding: 0 15rpx;
      font-size: 24rpx;
      color: #888;
      line-height: 1.6;
      border-radius: 4rpx;
      background-color: #f7f7f8;
    }

    .prices {
      display: flex;
      align-items: baseline;
      margin-top: 6rpx;
      font-size: 28rpx;

      .pay-price {
        margin-right: 10rpx;
        color: #cf4444;
      }

      .price {
        font-size: 24rpx;
        color: #999;
        text-decoration: line-through;
      }
    }

    .count {
      position: absolute;
      bottom: 0;
      right: 0;
      font-size: 26rpx;
      color: #444;
    }
  }
}

/* 配送及支付方式 */
.related {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 80rpx;
    font-size: 26rpx;
    color: #333;
  }

  .input {
    flex: 1;
    margin: 20rpx 0;
    padding-right: 20rpx;
    font-size: 26rpx;
    color: #666;
    text-align: right;
  }

  .item .text {
    width: 125rpx;
  }

  .picker {
    color: #666;
  }

  .picker::after {
    content: '\e6c2';
  }
}

/* 支付金额 */
.settlement {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 80rpx;
    font-size: 26rpx;
    color: #333;
  }

  .danger {
    color: #cf4444;
  }
}

/* 底部占位空盒子 */
.toolbar-height {
  box-sizing: content-box;
  height: 100rpx;
}

/* 底部工具栏 */
.toolbar {
  box-sizing: content-box;
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20rpx var(--window-bottom);
  height: 100rpx;
  border-top: 1rpx solid #ededed;
  background-color: #fff;

  .total-pay {
    font-size: 28rpx;
    color: #444;

    .price {
      margin-left: 8rpx;
      font-size: 40rpx;
      color: #cf4444;
    }

    .decimal {
      font-size: 75%;
    }
  }

  .button {
    width: 220rpx;
    font-size: 26rpx;
    color: #fff;
    text-align: center;
    line-height: 72rpx;
    border-radius: 72rpx;
    background-color: #27ba9b;

    &.disabled {
      opacity: 0.6;
    }
  }
}
</style>
